import {
  loginByUsername,
  logout,
  getUserInfo,
  getUserMenus
} from '../../api/login'
import {
  list
} from '@/api/dataDictionary'
import {
  getToken,
  setToken,
  removeToken,
  getPostName,
  setPostName,
  removePostName
} from '@/utils/auth'
import _test from './newMenuTest'

const user = {
  state: {
    user: '',
    userCode: '',
    status: '',
    code: '',
    token: getToken(),
    postName: getPostName(),
    sysid: '',
    name: '',
    dictList: [],
    avatar: '',
    introduction: '',
    roles: [],
    navmenu: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_USER_CODE: (state, userCode) => {
      state.userCode = userCode
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_SYSID: (state, sysid) => {
      state.sysid = sysid
    },
    SET_DICT_LIST: (state, data) => {
      state.dictList = data
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_NAVMENU: (state, menu) => {
      state.navmenu = menu
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({
      commit
    }, userInfo) {
      const username = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password, userInfo.uposId).then(response => {
          const data = response.Data
          commit('SET_TOKEN', data[0].Token)
          commit('SET_SYSID', data[0].SysId)
          commit('SET_USER_CODE', data[0].User.UserCode)
          // setToken(response.Data[0].username)
          // setToken(response.Data[0].token)
          setToken(response.Data[0].Token)
          setPostName(userInfo.uposName)
          commit('SET_NAVMENU', data[0].Auth.Menus)

          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    //拉取字典项缓存
    // itemList({ commit }) {
    //   return new Promise((resolve, reject) => {
    //     list({}).then(response => {
    //       const data = response.Data[0]
    //       commit('SET_DICT_LIST', data)
    //       sessionStorage.setItem('DICT_LIST', JSON.stringify(data))
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // 获取用户信息
    GetUserInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.Data[0]) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('获取用户信息失败')
          }
          const data = JSON.parse(response.Data[0])
          commit('SET_ROLES', 'admin')
          commit('SET_NAME', data.User.UserName)
          if (data.avatar) {
            commit('SET_AVATAR', data.avatar)
          } else {
            commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
          }
          commit('SET_USER_CODE', data.User.UserCode)
          commit('SET_INTRODUCTION', data.description)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
      // return new Promise((resolve, reject) => {
      //   commit('SET_ROLES', 'admin')
      //   resolve()
      // })
    },

    // 获取用户信息
    GetUserMenus({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        var response = {
          results: state.navmenu
        }

        // resolve(response)
        // if (state.navmenu === 0) {


        getUserMenus(state.token).then(response => {

          let tempList = Array.isArray(response.Data) ? [...response.Data] : [];
          for (let index = 0; index < tempList.length; index++) {
            const element = tempList[index];
            if (element.Title == '资讯推荐管理') {
              if (element.Children.length && element.Children.length > 1) {

                element.Children = element.Children.filter(val => {
                  return val.Title != '用户推荐文章信息'
                })
              }
            }
            if(element.Title==='词汇管理'){
              element.Children.push({
                ParentId: "149",
                Status: "0",
                CacheFlag: "1",
                Title: "标签消岐",
                Level: "2",
                Icon: "el-icon-menu",
                Id: "155",
                SortNo: 6,
                Code: "labelDisambiguation",
                name: "labelDisambiguation",
                meta:{
                title: "标签消岐",
                icon: "el-icon-menu",
                noCache: true
                },
                children: undefined,
                path: "labelDisambiguation"
              })
            }
            if(element.Title == '资讯管理'){
                element.Children.push({
                  ParentId: "133",
                  Status: "0",
                  CacheFlag: "1",
                  Title: "综合查询",
                  Level: "2",
                  Icon: "el-icon-menu",
                  Id: "134",
                  SortNo: 4,
                  Code: "integratedSearch"
                })
            }
          }

          // let doingMenu = {
          //   'ParentId': '-1',
          //   'Status': '0',
          //   'CacheFlag': '1',
          //   'Title': '数据统计',
          //   'Level': '1',
          //   'Children': [{
          //       'ParentId': '205',
          //       'Status': '0',
          //       'CacheFlag': '1',
          //       'Title': '资讯统计',
          //       'Level': '2',
          //       'Icon': 'el-icon-menu',
          //       'Id': '192',
          //       'SortNo': 1,
          //       'Code': 'newStatistics'
          //     },
          //     {
          //       'ParentId': '205',
          //       'Status': '0',
          //       'CacheFlag': '1',
          //       'Title': '资讯热榜',
          //       'Level': '2',
          //       'Icon': 'el-icon-menu',
          //       'Id': '193',
          //       'SortNo': 2,
          //       'Code': 'newsHotop'
          //     },
          //     {
          //       'ParentId': '205',
          //       'Status': '0',
          //       'CacheFlag': '1',
          //       'Title': '公告统计',
          //       'Level': '2',
          //       'Icon': 'el-icon-menu',
          //       'Id': '194',
          //       'SortNo': 3,
          //       'Code': 'publicStatistics'
          //     }
          //   ],
          //   'Icon': 'el-icon-menu',
          //   'Id': '205',
          //   'SortNo': 17,
          //   'Code': 'dataStatistics'
          // }

          const doingMenu = {}

          tempList = [...tempList, doingMenu]

          commit('SET_NAVMENU', tempList)
          // commit('SET_NAVMENU', _test.menuData)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
        // }

      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.Data[0].token)
    //       setToken(response.Data[0].token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        /*
         logout(state.token).then(() => {
         commit('SET_TOKEN', '')
         commit('SET_ROLES', [])
         commit('SET_NAVMENU', undefined)
         removeToken()
         resolve()
         }).catch(error => {
         reject(error)
         })*/
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_NAVMENU', undefined)
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_NAVMENU', undefined)
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({
      commit
    }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.Data[0]
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }
  }
}

export default user
